#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <functional>
#include <cstring>
#include <cerrno>
#include <strings.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"
#include "Common.hpp"
#include "InetAddr.hpp"

using namespace LogModule;
using func_t = std::function<std::string(const std::string)>;

const static int gsockfd = -1;
const static uint16_t gdefaultport = 8080;

class UdpServer
{
public:
    UdpServer(func_t func, uint16_t port = gdefaultport)
        : _sockfd(gsockfd), _addr(port), _isrunning(false), _func(func)
    {}

    ~UdpServer()
    {
        if (_sockfd > gsockfd)
        {
            ::close(_sockfd);
        }
    }

    void InitServer()
    {
        // 1. 创建socket
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket: " << strerror(errno);
            Die(SOCKET_ERR);
        }
        LOG(LogLevel::INFO) << "socket success, sockfd is: " << _sockfd;

        // 2. bind网络信息到内核中
        int n = ::bind(_sockfd, _addr.NetAddr(), _addr.NetAddrLen());
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind: " << strerror(errno);
            Die(BIND_ERR);
        }
        LOG(LogLevel::INFO) << "bind success";
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            char buffer[1024];
            struct sockaddr_in client;
            socklen_t len = sizeof(client);

            // 1. 接收客户端发来的消息
            ssize_t n = ::recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&client), &len);
            if (n > 0)
            {
                buffer[n] = 0;
                
                // 2. 执行任务
                std::string message = _func(buffer);

                // 3. 返回信息给客户端
                ::sendto(_sockfd, message.c_str(), message.size(), 0, CONV(&client), sizeof(client));
            }
        }
        _isrunning = false;
    }

private:
    int _sockfd;
    InetAddr _addr;
    bool _isrunning;

    // 业务: 回调方法
    func_t _func;
};